#!/bin/sh

{{"{{"}}$stable := gets "/{{ getv "/rolling/APP_NAME/stable/id" }}/*"{{"}}"}}
{{"{{"}}$candidate := gets "/{{ getv "/rolling/APP_NAME/candidate/id" }}/*"{{"}}"}}

UPSTREAM_FILE=/etc/nginx/sites-enabled/00-upstream
BLEND_PERCENT={{getv "/rolling/APP_NAME/blendpercent"}}
STABLE_COUNT={{"{{"}}len $stable{{"}}"}}
CANDIDATE_COUNT={{"{{"}}len $candidate{{"}}"}}

[ "$BLEND_PERCENT" == "" ] \
  || [ "$BLEND_PERCENT" -lt 0 ] \
  || [ "$BLEND_PERCENT" -gt 100 ] \
  && { BLEND_PERCENT=0; }
[ "$STABLE_COUNT" == "" ] && { STABLE_COUNT=0; }
[ "$CANDIDATE_COUNT" == "" ] && { CANDIDATE_COUNT=0; }

STABLE_CLAUSE=" down"
if [ "$STABLE_COUNT" -gt 0 ]; then
  STABLE_WEIGHT=$(( (100 - ${BLEND_PERCENT}) / STABLE_COUNT))
  [ "$STABLE_WEIGHT" -gt 0 ] && { STABLE_CLAUSE=" weight=${STABLE_WEIGHT}"; }
fi

CANDIDATE_CLAUSE=" down"
if [ "$CANDIDATE_COUNT" -gt 0 ]; then
  CANDIDATE_WEIGHT=$(( ${BLEND_PERCENT} / CANDIDATE_COUNT))
  [ "$CANDIDATE_WEIGHT" -gt 0 ] && { CANDIDATE_CLAUSE=" weight=${CANDIDATE_WEIGHT}"; }
fi

cat <<ENDOFTEMPLATE > ${UPSTREAM_FILE}
upstream rollingservices {
  least_conn;
  server 127.0.0.1 down;
  {{"{{"}}range $stable{{"}}"}}
  server {{"{{"}}.Value{{"}}"}}${STABLE_CLAUSE};{{"{{"}}end{{"}}"}}

  {{"{{"}}range $candidate{{"}}"}}
  server {{"{{"}}.Value{{"}}"}}${CANDIDATE_CLAUSE};{{"{{"}}end{{"}}"}}
}
ENDOFTEMPLATE

CONFIG_TEST=$(nginx -t 2>&1)
if [ "$?" -gt 0 ]; then
  echo "$CONFIG_TEST"
  exit 1
fi

sv reload nginx
